import { BillApi } from '@/api/Bill.api.js'
import { SysWelfarePercentEmployeeCommercialConfigApi } from '@/api/SysWelfarePercentEmployeeCommercialConfig.api.js'
import { SysWelfarePercentNoCommercialConfigApi } from '@/api/SysWelfarePercentNoCommercialConfig.api.js'
import { FormShangbaoFilter, FormShangbaoFilterItem } from './EBformData.js'
import { shangbaoThead, shangbaojiluThead } from './EBtableHead.js'
import DeleteEmployeeModal from './modal/deleteEmployeeModal.vue'
import _cloneDeep from 'clone-deep'
import { Common } from '@/utils/common.js'
import { EBbase } from './EBbase.js'
import moment from 'moment'

export default {
  props: {
    serviceFeeType: {
      type: Number,
      default: 0
    },
    isInsuranceInfoSet: {
      type: Boolean,
      default: false
    }
  },

  components: {
    DeleteEmployeeModal
  },

  computed: {
    manageTypeValue () {
      var currentCustomerManage = JSON.parse(localStorage.getItem('currentCustomerManage')) // 缓存里的公司部分信息
      return currentCustomerManage.typeValue
    }
  },

  data () {
    return {
      isOnlyView: true,
      canEditor: null,
      isCanSave: true,
      employeeId: '',
      insuranceId: '', // 保险ID
      isBatch: false,
      formShangbaoFilter: _cloneDeep(FormShangbaoFilter),
      formShangbaoFilterItem: _cloneDeep(FormShangbaoFilterItem),
      // formShangbao: _cloneDeep(FormShangbao),
      // formShangbaoItem: _cloneDeep(FormShangbaoItem),
      thead: _cloneDeep(shangbaoThead),
      shangbaojiluThead: _cloneDeep(shangbaojiluThead),
      tableData: [],
      recordTableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10 // 当前页面展示条数
      },
      rules: {
        securityGUID: [
          { required: true, message: '请选择商保编号', trigger: 'select' }
        ],
        insuredTime: [
          { required: true, message: '请选择起保时间', trigger: 'select' }
        ]
      },
      arrListDown: {
        securityNoList: []
      },
      formShangbaoTable: [],
      isEdit: false,
      deleteEmployeeTitle: '是否确认删除该条员工的商保信息？',
      selectContractId: '', // 选中要删除的员工合同ID
      employeeBasicInfo: null,
      isFromRoster: null,
      shangbaoDisabledDate: {
        disabledDate (date) {
          const disabledDay = date.getDate()
          const disabledMonth = date.getMonth()
          const today = (new Date()).getDate()
          const month = (new Date()).getMonth()
          return !(disabledDay == today && disabledMonth == month) && !(disabledDay == 1 && disabledMonth !== month);
        }
      }
    }
  },

  mounted () {
    this.employeeId = this.$route.query.employeeId // 员工ID
    this.companyId = this.$route.query.companyId // 公司ID
    this.companyName = this.$route.query.companyName // 公司名称
    this.isFromRoster = this.$route.query.isFromRoster // 是否从员工管理页面过来
    this.canEditor = !!(this.$route.query.checkEmployeeNum || this.$route.query.isCreateNew || this.$route.query.isBatch)
    this.selectedEmployeeId = JSON.parse(localStorage.getItem('selectedEmployeeId')) // 选中的员工
    this.employeeBasicInfo = JSON.parse(localStorage.getItem('employeeBasicInfo')) // 当前员工基本信息
    this.isBatch = this.$route.query.isBatch // 是否批量

    this.formShangbaoFilter.employeeGUID = this.$route.query.employeeId // 员工ID

    if (this.$route.query.isCreateNew) { // isCreateNew参数为true时，为新增
      this.isOnlyView = false
    }

    if (this.$route.query.isOnlyView) { // 仅查看详情时，去掉'操作'列
      this.thead.pop()
    }

    if (this.canEditor) { // 可编辑状态时，去掉'被替换人姓名'，'被替换人身份证'两列
      var newThead = []
      this.thead.map(item => {
        if (item.key !== 'originalEmployeeName' && item.key !== 'originalEmployeeIdCardNo') {
          newThead.push(item)
        }
      })
      this.thead = newThead
    } else {
      this.employeeInsureDetails()
    }

    // if (this.$route.query.employeeId) {
    //   this.query()
    // }
    this.getSecurityNoList()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    async handleSubmit (name) {
      console.log('this.formShangbaoFilter: ', this.formShangbaoFilter)
      let res = await SysWelfarePercentEmployeeCommercialConfigApi.save(this.formShangbaoFilter)
      if (res.status === 200 && res.data.success) {
        // this.$Message.success(res.data.message)
        this.$Message.success({
          content: res.data.message,
          duration: 1.5,
          closable: true
        })
        this.query()
        setTimeout(() => {
          this.isEdit = false
        }, 1500)
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    async handleBatchSubmit (name) {
      console.log('this.formShangbaoFilter: ', this.formShangbaoFilter)
      let res = await SysWelfarePercentEmployeeCommercialConfigApi.batchSave({ ...this.formShangbaoFilter, ...{ EmployeeIdList: this.selectedEmployeeId } })
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.queryBatch()
        setTimeout(() => {
          this.isEdit = false
        }, 1500)
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 获取单个员工商保参保信息配置
    async query () {
      var params = {
        employeeId: this.employeeId
      }
      let res = await SysWelfarePercentEmployeeCommercialConfigApi.getList(params)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        if (!this.tableData.length && !this.isOnlyView) {
          this.isEdit = true
        }
      } else {
        this.tableData = [] // 无数据
      }
    },

    // 获取批量员工商保参保信息配置
    async queryBatch () {
      var params = {
        employeeIdList: this.selectedEmployeeId
      }
      let res = await SysWelfarePercentEmployeeCommercialConfigApi.getBatchList(params)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        if (!this.tableData.length && !this.isOnlyView) {
          this.isEdit = true
        }
      } else {
        this.tableData = [] // 无数据
      }
    },

    // 获取参保编号列表
    async getSecurityNoList () {
      var params = {
        SecurityType: 3,
        CompanyGUID: this.companyId
      }
      let res = await SysWelfarePercentNoCommercialConfigApi.getSecurityNoList(params)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.securityNoList = res.data.data
        // console.log('参保编号列表1:' , this.arrListDown.securityNoList)
      } else {
        // console.log('参保编号列表2:' , res.data.data.message)
        this.arrListDown.securityNoList = [] // 无数据
      }
    },

    // 获取参保编号列表
    async getModel (selectId) {
      if (selectId) {
        var self = this
        var params = {
          id: selectId
        }
        let res = await SysWelfarePercentNoCommercialConfigApi.getModel(params)
        console.log('resxxxxxxxxxxxx: ', res)
        if (res.status === 200 && res.data.success) {
          var result = res.data.data
          this.formShangbaoFilter.totalAmount = result.totalAmount
        } else {
        }
      }
    },

    // 上一步
    handlepageUp () {
      if (this.serviceFeeType === 3) { // 参保种类选择了'商业保险'
        Common.pageUp(this, 3)
      } else if (this.serviceFeeType === 13) { // 参保种类选择了'社保+商保'
        Common.pageUp(this, 4)
      } else {
        Common.pageUp(this)
      }
    },

    // 下一步
    handlepageDown () {
      Common.pageDown(this)
    },

    // // 删除一行
    // handleDelRow (rowIndex) {
    //   // this.tableData.splice(rowIndex, 1)
    // },

    // 修改
    handleModify () {
      this.$emit('handleModify', 6)
    },

    // 修改当前条
    handleEditRow (row) {
      console.log('商保修改当前条row: ', row)
      this.isEdit = true
      for (var item in row) {
        this.formShangbaoFilter[item] = row[item]
      }
    },

    // // 删除员工商保信息-显示弹窗
    // handleSureDelete (id) {
    //   this.$refs.DeleteEmployeeModal.isShowDeleteEmployeeModal = true
    //   this.$refs.DeleteEmployeeModal.selectDelId = id
    // },

    // 删除员工商保信息(单个)-确认删除
    async handleSureDelete (id) {
      let res = await SysWelfarePercentEmployeeCommercialConfigApi.delete({ id: id })
      if (res.data.success) {
        this.$Message.success(res.data.message)
        // this.query()
        if (this.$route.query.isBatch) {
          this.queryBatch()
        } else {
          this.query()
        }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 删除员工商保信息(批量)-确认删除
    async handleSureBatchDelete (securityGUID) {
      var paramObj = {
        SecurityGUID: securityGUID,
        EmployeeIdList: this.selectedEmployeeId
      }
      console.log('🌙', paramObj)
      let res = await SysWelfarePercentEmployeeCommercialConfigApi.batchDelete(paramObj)
      if (res.data.success) {
        this.$Message.success(res.data.message)
        if (this.$route.query.isBatch) {
          this.queryBatch()
        } else {
          this.query()
        }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 新增商保
    handleCreat () {
      Object.keys(this.formShangbaoFilter).forEach(key => {
        if (key !== 'id' && key !== 'employeeGUID' && key !== 'insuredTime') {
          this.formShangbaoFilter[key] = '' // 表单内容置空
        }
      })
      this.formShangbaoFilter.employeeGUID = this.employeeId
      this.isEdit = true
    },

    // 新增商保-批量
    handleBatchCreat () {
      Object.keys(this.formShangbaoFilter).forEach(key => {
        if (key !== 'id' && key !== 'insuredTime') {
          this.formShangbaoFilter[key] = '' // 表单内容置空
        }
      })

      this.formShangbaoFilter.employeeIdList = this.selectedEmployeeId
      this.isEdit = true
    },

    // 返回员工花名册列表
    goEmployeeBookList () {
      EBbase.goEmployeeBookList(this.$router, this.companyId, this.companyName)
    },

    // 时间选择控件
    handleChangeDatePicker (model, value) {
      console.log('时间选择控件 model: ' + model + ', value: ' + value)
      this.formShangbaoFilter[model] = value
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },

    // 获取社保记录
    async employeeInsureDetails (selectId) {
      var params = {
        CustomerId: this.companyId,
        EmployeeId: this.employeeId,
        Category: 4, // 1-社保，2-公积金，3-商保
        IdCardType: this.employeeBasicInfo.idType,
        IdCardNo: this.employeeBasicInfo.idCardNo,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      // var params = {
      //   CustomerId: '946FB851-F1AC-E911-80BF-509A4C9F0611',
      //   EmployeeId: '36B616A7-B1AD-E911-80BF-509A4C9F0611',
      //   Category: 4, // 1-社保，2-公积金，4-商保
      //   IdCardType: 0,
      //   IdCardNo: '434121199612064216',
      //   HasPaging: true,
      //   PageIndex: 1,
      //   PageSize: 10,
      // }
      let res = await BillApi.employeeInsureDetails(params)
      console.log('获取社保记录res: ', res)
      if (res.status === 200 && res.data.success) {
        this.recordTableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.recordTableData.map(row => {
          row.insureItems.map(item => { // 循环解析insureItems里面的companyFee、employeeFee值并赋到相应的key
            var sumStr = ''
            if (item.companyFee) {
              Object.keys(item.companyFee).forEach(key => {
                sumStr = item.category + 'companyFee' + key
                row[sumStr] = item.companyFee[key]
              })
            }

            if (item.employeeFee) {
              Object.keys(item.employeeFee).forEach(key => {
                sumStr = item.category + 'employeeFee' + key
                row[sumStr] = item.employeeFee[key]
              })
            }
          })
        })
        console.log('🐟 this.recordTableData: ', this.recordTableData)
      }
    },

    // 返回员工花名册列表
    goEmployeeBookList () {
      EBbase.goEmployeeBookList(this.$router, this.companyId, this.companyName)
    },

    // 返回员工管理
    goRoster () {
      EBbase.goRoster(this.$router)
    }
  }
}
